<?php

namespace app\backend\services\auth;

use app\backend\model\Admin;
use think\App;
use think\exception\HttpException;
use think\Request;
use think\Response;
use Closure;

class Middleware
{

    /**
     * @var Authority $auth
     */
    private $auth;

    public function __construct(App $app)
    {
        $this->auth = $app->invokeClass(Authority::class);
        $app->bind('auth', $this->auth);

        if (session('?admin')) {
            $admin = Admin::find(session('admin.id'));
            $roles = [];
            foreach ($admin->roles() as $r) {
                $roles[] = $r;
            }
            $this->auth->setUser($admin)->administrator($admin->id === Admin::ADMIN)->assignRole($roles);
        }

        $menus = include root_path('app/backend') . 'menu.php';
        $this->auth->addPermissions($menus);
    }

    /**
     * @param Request $request
     * @param Closure $next
     *
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle($request, Closure $next)
    {
        // 权限校验
        $rule = trim($request->url(), "\\/");
        if ($this->auth->can( ['route'=>$rule, 'method' => $request->method()] )) {
            return $next($request);
        }

        if (null === $this->auth->user()) {
            return redirect('/backend/login/index');
        }

        throw new HttpException('403', '没有访问权限');
    }

}
